//
//  PublishBlogController.swift
//  SinaBlog
//
//  Created by 有何不可 on 16/1/10.
//  Copyright © 2016年 有何不可. All rights reserved.
//

import UIKit
import SnapKit

class PublishBlogController: UIViewController, UITextViewDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
    
    var model: OauthModel?

    override func viewDidLoad() {
        super.viewDidLoad()
       
        // Do any additional setup after loading the view.
        setNavBarItem()
        //这两个的层次结构不能变,否则会影响视图,这是由于在addSubView的顺序也就不一样了 图层的先后顺序不对
        setTextView()
        setToolbar()
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "changeToolbarFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
    }
    
    @objc private func changeToolbarFrame(notify: NSNotification) {
        
//        print(notify.userInfo)
        
        /*
            UIKeyboardFrameBeginUserInfoKey: NSRect: {{0, 667}, {375, 258}},
            UIKeyboardCenterEndUserInfoKey: NSPoint: {187.5, 538}, 
            UIKeyboardBoundsUserInfoKey: NSRect: {{0, 0}, {375, 258}}, 
            UIKeyboardFrameEndUserInfoKey: NSRect: {{0, 409}, {375, 258}}, 
            UIKeyboardAnimationDurationUserInfoKey: 0.25,
            UIKeyboardCenterBeginUserInfoKey:   NSPoint: {187.5, 796}, 
            UIKeyboardAnimationCurveUserInfoKey: 7,
            UIKeyboardIsLocalUserInfoKey: 1
        */
        
        let rect = notify.userInfo!["UIKeyboardFrameEndUserInfoKey"]!.CGRectValue
        
        let time = notify.userInfo!["UIKeyboardAnimationDurationUserInfoKey"]!.doubleValue

        self.toolbar.snp_updateConstraints { (make) -> Void in
            
            make.bottom.equalTo(-(kScreenHeight - rect.origin.y))
        }

        //改变它的约束,需要对其进行刷新才行,不能将约束直接放入动画中
        
        UIView.animateWithDuration(time) { () -> Void in
            
            self.toolbar.layoutIfNeeded()
        }
        
    }
    
    deinit {
        
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    private lazy var textView: PublishView = PublishView()
    private lazy var chooseView: ChooseView =  {
        
        let choose = ChooseView()
        //在这里会掉,同时也要注意闭包中的循环引用 循环引用解决方案有2种,unowned,和weak.
        //weak ===== OC中weak
        //unowned ===== OC中assign
        choose.callBack = { [weak self] in
            
           self!.choosePicture()
            
        }
        return choose
    }()
    private lazy var toolbar = UIToolbar()
}
// MARK: --navigationBar的创建
extension PublishBlogController {
    
    private func setNavBarItem() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: .Plain, target: self, action: "cancle")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: .Plain, target: self, action: "publish")
        
        navigationItem.rightBarButtonItem?.enabled = false
        
        navigationItem.titleView = setTitleText()
        
    }
    
    private func setTitleText() -> UILabel {
        
        let titleText = UILabel()
        
        let name = model?.screen_name ?? ""
        
        let str = "发布微博\n\(name)"
        
        titleText.frame = CGRectMake(0, 0, 200, 44)
        
        titleText.textAlignment = NSTextAlignment.Center
        
        let strAttribute = NSMutableAttributedString(string:str)
        
        strAttribute.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(15), range: NSMakeRange(0, 4))
        
        let attributes = [NSFontAttributeName: UIFont.systemFontOfSize(12), NSForegroundColorAttributeName: UIColor.orangeColor()]
        
        strAttribute.addAttributes(attributes, range: NSMakeRange(4, str.characters.count - 4))
        
        titleText.numberOfLines = 0
        
        titleText.attributedText = strAttribute
        
        return titleText
    }
    
    @objc private func cancle() {
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func publish() {
        
        print("发微博")
    }

}

//MARK: --TextView的创建和 方法的实现
extension PublishBlogController {
    
    private func setTextView() {
        
        view.addSubview(textView)
        
        textView.snp_makeConstraints { (make) -> Void in
            
            make.top.equalTo(view.snp_top)
            make.bottom.equalTo(view.snp_bottom)
            make.right.equalTo(view.snp_right)
            make.left.equalTo(view.snp_left)
        }
        textView.holdString = "分享微博... ..."
        
        textView.font = UIFont.systemFontOfSize(14)
        //让textView可以滚动
        textView.alwaysBounceVertical = true
        //滚动让键盘消失
        textView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        
        textView.delegate = self
        
        textView.addSubview(chooseView)
        
        chooseView.snp_makeConstraints { (make) -> Void in
            
            make.top.equalTo(textView.snp_top).offset(100)
            make.left.equalTo(textView.snp_left).offset(margin)
            make.width.equalTo(kScreenWidth - 2 * margin)
            make.height.equalTo(chooseView.snp_width)
            
        }
    }
    
    //textView的代理实现
    
    func textViewDidChange(textView: UITextView) {
        
        if  self.textView.hasText() {
            
            self.textView.holdString = ""
        }else {
            
            self.textView.holdString = "分享微博... ..."
        }
        
        self.textView.setNeedsDisplay()
        
        navigationItem.rightBarButtonItem?.enabled = self.textView.hasText()
        
    }
}

// MARK: --创建toolbar
extension PublishBlogController {
    
    private func setToolbar() {
        
        view.addSubview(toolbar)
        
        toolbar.snp_makeConstraints { (make) -> Void in
            
            make.bottom.equalTo(view.snp_bottom)
            make.height.equalTo(44)
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
        }
        
        toolbar.backgroundColor = UIColor(red: 230 / 255.0, green: 230 / 255.0, blue: 230 / 255.0, alpha: 1.0)
        
        // 添加item
        let itemSettings = [["imageName": "compose_toolbar_picture", "action": "choosePicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "action": "inputEmoticon"],
            ["imageName": "compose_addbutton_background"]]

        var items: [UIBarButtonItem] = [UIBarButtonItem]()
        
        for itemName in itemSettings {
            
            let imageName = itemName["imageName"]!
            
            let btn = UIButton(type: .Custom)
            
            btn.setImage(UIImage(named: imageName), forState: .Normal)
            btn.setImage(UIImage(named: "\(imageName)_highlighted"), forState: .Highlighted)
            
            if let action = itemName["action"] {
                
                btn.addTarget(self, action: Selector(action), forControlEvents: .TouchUpInside)
            }
            
            btn.sizeToFit()
            
            let fixableItem = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
            
            items.append(UIBarButtonItem(customView: btn))
            items.append(fixableItem)
        }
        
        items.removeLast()
        
        toolbar.items = items
    }
    //MARK: --toolBar的按钮方法的实现
    @objc private func choosePicture() {
        
        let picture = UIImagePickerController()
        
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary) {
            
            presentViewController(picture, animated: true, completion: nil)
        }
        
        picture.delegate = self
    }
    
    @objc private func inputEmoticon() {
        
        
    }
    
    //MARK: --UIImagePickerController代理方法实现,监听获取数据;
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        chooseView.addimages(image)
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
}
